﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Data.SqlClient;
using Manager.App_Code.DAL;
using Microsoft.SqlServer.Management.Common;

using Microsoft.SqlServer.Management.Smo;
using GalaBuilding.Component;
using System.Xml;


namespace Manager.FormAdd_Edit
{
    public partial class frm_RestoreDatabase : DevExpress.XtraEditors.XtraForm
    {
        public frm_RestoreDatabase()
        {
            InitializeComponent();
        }

        QuanTriHeThongDAL func = new QuanTriHeThongDAL();

        private void btninputfile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openfiledlg = new OpenFileDialog();
            openfiledlg.Filter = "BAK|*.bak|TRN|*.trn";
            string resultdlg;
            if (openfiledlg.ShowDialog() == DialogResult.OK)
            {
                resultdlg = openfiledlg.FileName; ;
                txtpathfile.Text = resultdlg.ToString();
            }
        }

        SqlConnection _conn;
        private void btnres_Click(object sender, EventArgs e)
        {
            //SqlParameter[] param1 = { new SqlParameter("@PathFile", txtpathfile.Text) };
            //try
            //{
            //    func.CloseConnection();
            //    func.Connetmaster();
            //    func.call_procedure_P_noreturn("restorebackup", param1);
            //    MessageBox.Show("Restore thành công");
            //}
            //catch
            //{
            //    MessageBox.Show("Restore thất bại");
            //}

            XmlDocument xmlRed = XML.XMLReader("Connection.xml");
            XmlElement xmlEle = xmlRed.DocumentElement;

            try
            {
                if (xmlEle.SelectSingleNode("costatus").InnerText == "true")
                {
                    _conn = new SqlConnection("Data Source=" + xmlEle.SelectSingleNode("servname").InnerText + ";Initial Catalog=" + xmlEle.SelectSingleNode("database").InnerText + ";Integrated Security=True;");
                }
                else
                {
                    _conn = new SqlConnection("Data Source=" + xmlEle.SelectSingleNode("servname").InnerText + ";Initial Catalog=" + xmlEle.SelectSingleNode("database").InnerText + ";User Id=" + xmlEle.SelectSingleNode("username").InnerText + ";Password=" + xmlEle.SelectSingleNode("password").InnerText + ";");
                }

                Utilities.DatabaseName = xmlEle.SelectSingleNode("database").InnerText;

                //OpenConnection();
            }
            catch
            {
                MessageBox.Show("Lỗi kết nối đến cơ sở dữ liệu! Vui lòng thiết lập lại kết nối!!!", "ERROR", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);

                Frm_Connection frm = new Frm_Connection();
                frm.ShowDialog();
            }

            try
            {

                this._conn.Open();


                string UseMaster = "USE master";
                SqlCommand UseMasterCommand = new SqlCommand(UseMaster, this._conn);
                UseMasterCommand.ExecuteNonQuery();

                string Alter1 = @"ALTER DATABASE DucMinh_Hotel SET Single_User WITH Rollback Immediate";
                SqlCommand Alter1Cmd = new SqlCommand(Alter1, this._conn);
                Alter1Cmd.ExecuteNonQuery();

                string Restore = @"RESTORE DATABASE DucMinh_Hotel FROM DISK = N'" + txtpathfile.Text + @"' WITH  FILE = 1,  NOUNLOAD,  STATS = 10";
                SqlCommand RestoreCmd = new SqlCommand(Restore, this._conn);
                RestoreCmd.ExecuteNonQuery();

                string Alter2 = @"ALTER DATABASE DucMinh_Hotel SET Multi_User";
                SqlCommand Alter2Cmd = new SqlCommand(Alter2, this._conn);
                Alter2Cmd.ExecuteNonQuery();

                MessageBox.Show("Successfully");


            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
 
            }



    //        try
    //        {




    //            MessageBox.Show("Restore operation started");
    //            Restore restore = new Restore();
    //            //Set type of backup to be performed to database
    //            restore.Database = "DucMinh_Hotel";
    //            restore.Action = RestoreActionType.Database;
    //            //Set up the backup device to use filesystem.         
    //            restore.Devices.AddDevice(txtpathfile.Text, DeviceType.File);
    //            //set ReplaceDatabase = true to create new database
    //            //regardless of the existence of specified database
    //            restore.ReplaceDatabase = true;
    //            //If you have a differential or log restore to be followed,
    //            //you would specify NoRecovery = true
    //            restore.NoRecovery = false;
    //            //if you want to restore to a different location, specify
    //            //the logical and physical file names
    //            restore.RelocateFiles.Add(new RelocateFile("DucMinh_Hotel",
    //@"C:\Temp\DucMinh_Hotel_BackUp.mdf"));
    //            restore.RelocateFiles.Add(new RelocateFile("DucMinh_Hotel_Log",
    //@"C:\Temp\DucMinh_Hotel_BackUp_Log.ldf"));
    //            ServerConnection connection = new
    //ServerConnection(this._conn);
    //            //my SQL user doesnt have sufficient permissions,
    //            //so i am using my windows account
    //            //connection.LoginSecure = true;
    //           // connection.LoginSecure = false;
    //       //     connection.Login = xmlEle.SelectSingleNode("servname").InnerText;
    //            //connection.Password = "testuser";
    //            Server sqlServer = new Server(connection);
    //            //SqlRestore method starts to restore database           
    //            restore.SqlRestore(sqlServer);
    //            MessageBox.Show("Restore operation succeeded");
    //        }
    //        catch (Exception ex)
    //        {
    //            MessageBox.Show("Restore operation failed");
    //            MessageBox.Show(ex.Message);

    //        }
    //        //     Console.ReadLine();


        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}